package jehc.cloud.common.base.dynamic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Desc DynamicDataSource
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Primary
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Autowired
    @Qualifier("dataSourceMaster")
    private DataSource dataSourceMaster;

    @Autowired
    @Qualifier("dataSourceSlave")
    private DataSource dataSourceSlave;

    /**
     * 这个是主要的方法，返回的是生效的数据源名称
     */
    @Override
    protected Object determineCurrentLookupKey() {
        String dbType = DataSourceContextHolder.getDbType();
        log.info("动态切换数据源："+dbType);
        return dbType;
    }

    /**
     *
     */
    @Override
    public void afterPropertiesSet() {
        log.info("after set datasource...");
        Map<Object, Object> map = new HashMap<>();
        map.put("dataSourceMaster", dataSourceMaster);
        map.put("dataSourceSlave", dataSourceSlave);
        setTargetDataSources(map);
        setDefaultTargetDataSource(dataSourceMaster);
        DataSourceContextHolder.clearDbType();
        log.info("after set clean datasource threadLocal success...");
        super.afterPropertiesSet();
    }
}
